<script setup lang="ts">
import {ref, reactive, onMounted} from 'vue';
import {useRouter} from 'vue-router';
import {Search, Plus, Download} from '@element-plus/icons-vue';
import {ElMessage, ElLoading} from 'element-plus';
import {dataAPI} from '@/http/leancloud';

/**
 * 此页面对应订单列表
 */

const router = useRouter();

// 订单状态选项
const orderStatusOptions = [
  {label: '全部', value: 'all'},
  {label: '待配载', value: 'waiting_load'},
  {label: '待接单', value: 'waiting_accept'},
  {label: '待提货', value: 'waiting_pickup'},
  {label: '运输中', value: 'in_transit'},
  {label: '待签收', value: 'waiting_sign'},
  {label: '已完成', value: 'completed'},
  {label: '已取消', value: 'cancelled'}
];

// 付款方式选项
const paymentMethodOptions = [
  {label: '全部', value: 'all'},
  {label: '寄付', value: 'sender_pay'},
  {label: '到付', value: 'receiver_pay'},
  {label: '月结', value: 'monthly'},
  {label: '欠款', value: 'debt'}
];

// 站点选项
const stationOptions = [
  {label: '义乌站', value: '义乌站'},
  {label: '北京站', value: '北京站'},
  {label: '上海站', value: '上海站'},
  {label: '广州站', value: '广州站'},
  {label: '杭州站', value: '杭州站'},
  {label: '成都站', value: '成都站'}
];

// 订单状态筛选
const orderStatus = ref('all');
// 付款方式筛选
const paymentMethod = ref('all');
// 启用状态
const enabled = ref('all');

// 搜索条件
const searchForm = reactive({
  orderNumber: '',
  waybillNumber: '',
  senderInfo: '',
  receiverInfo: '',
  senderStation: '',
  destinationStation: '',
  transferStation: '',
  startDate: '',
  endDate: ''
});

// 表格数据
const tableData = ref([]);
const loading = ref(false);
const total = ref(0);
const pageSize = ref(10);
const currentPage = ref(1);

// 订单状态码映射（与App端保持一致）
const orderStatusMap: Record<string, number> = {
  'all': -1,
  'waiting_load': 0,
  'waiting_accept': 0,
  'waiting_pickup': 1,
  'in_transit': 2,
  'waiting_sign': 5,
  'completed': 6,
  'cancelled': 7
};

// 付款方式映射（与App端保持一致）
const paymentMethodMap: Record<string, number> = {
  'all': -1,
  'sender_pay': 2,  // 寄付（现付）
  'receiver_pay': 0, // 到付
  'monthly': 3,     // 月结
  'debt': 1         // 欠款（提付）
};

// 根据状态获取标签类型
const getStatusTagType = (status: string) => {
  const statusMap: Record<string, string> = {
    waiting_load: 'warning',
    waiting_accept: 'info',
    waiting_pickup: 'info',
    in_transit: 'primary',
    waiting_sign: 'warning',
    completed: 'success',
    cancelled: 'danger'
  };
  return statusMap[status] || 'info';
};

// 状态文本映射
const statusTextMap: Record<string, string> = {
  waiting_load: '待配载',
  waiting_accept: '待接单',
  waiting_pickup: '待提货',
  in_transit: '运输中',
  waiting_sign: '待签收',
  completed: '已完成',
  cancelled: '已取消'
};

// 处理搜索
const handleSearch = async () => {
  try {
    loading.value = true;

    // 构建查询条件
    const query: any = {};

    // 订单号查询
    if (searchForm.orderNumber) {
      query.orderNo = {$regex: searchForm.orderNumber};
    }

    // 发货人信息查询（姓名或电话）
    if (searchForm.senderInfo) {
      query.$or = query.$or || [];
      query.$or.push(
          {senderName: {$regex: searchForm.senderInfo}},
          {senderPhone: {$regex: searchForm.senderInfo}}
      );
    }

    // 收货人信息查询（姓名或电话）
    if (searchForm.receiverInfo) {
      query.$or = query.$or || [];
      query.$or.push(
          {receiverName: {$regex: searchForm.receiverInfo}},
          {receiverPhone: {$regex: searchForm.receiverInfo}}
      );
    }

    // 站点查询
    if (searchForm.senderStation) {
      query.senderAddress = {$regex: searchForm.senderStation};
    }

    if (searchForm.destinationStation) {
      query.receiverAddress = {$regex: searchForm.destinationStation};
    }

    // 日期范围查询
    if (searchForm.startDate && searchForm.endDate) {
      query.orderTime = {
        $gte: {
          __type: "Date",
          iso: new Date(searchForm.startDate).toISOString()
        },
        $lte: {
          __type: "Date",
          iso: new Date(searchForm.endDate).toISOString()
        }
      };
    } else if (searchForm.startDate) {
      query.orderTime = {
        $gte: {
          __type: "Date",
          iso: new Date(searchForm.startDate).toISOString()
        }
      };
    } else if (searchForm.endDate) {
      query.orderTime = {
        $lte: {
          __type: "Date",
          iso: new Date(searchForm.endDate).toISOString()
        }
      };
    }

    // 订单状态查询
    if (orderStatus.value !== 'all') {
      query.status = orderStatusMap[orderStatus.value];
    }

    // 付款方式查询
    if (paymentMethod.value !== 'all') {
      query.paymentMethod = paymentMethodMap[paymentMethod.value];
    }

    console.log('查询条件:', query);

    // 调用LeanCloud API查询订单
    const orders = await dataAPI.query('Order', query);
    console.log('查询结果:', orders);

    if (orders && orders.length > 0) {
      // 转换数据格式
      tableData.value = orders.map((order: any) => {
        // 订单状态码转换为前端状态
        let statusCode;
        switch (order.status) {
          case 0:
            statusCode = 'waiting_accept';
            break;
          case 1:
            statusCode = 'waiting_pickup';
            break;
          case 2:
            statusCode = 'in_transit';
            break;
          case 3:
            statusCode = 'in_transit';
            break; // 可能需要调整
          case 4:
            statusCode = 'in_transit';
            break; // 可能需要调整
          case 5:
            statusCode = 'waiting_sign';
            break;
          case 6:
            statusCode = 'completed';
            break;
          default:
            statusCode = 'waiting_accept';
        }

        // 付款方式转换
        let paymentText;
        switch (order.paymentMethod) {
          case 0:
            paymentText = '到付';
            break;
          case 1:
            paymentText = '提付';
            break;
          case 2:
            paymentText = '寄付';
            break;
          case 3:
            paymentText = '月结';
            break;
          default:
            paymentText = '现付';
        }

        // 格式化日期
        const orderDate = order.orderTime && order.orderTime.__type === 'Date'
            ? new Date(order.orderTime.iso).toLocaleString()
            : '';

        return {
          id: order.objectId,
          waybillNumber: order.orderNo,
          sender: order.senderName,
          senderPhone: order.senderPhone,
          senderAddress: order.senderAddress,
          senderStation: order.senderAddress?.split('-')[0] || '',
          transferStation: order.route?.includes('-') ? order.route.split('-')[1] : '-',
          destinationStation: order.receiverAddress?.split('-')[0] || '',
          receiver: order.receiverName,
          receiverPhone: order.receiverPhone,
          receiverAddress: order.receiverAddress,
          cargoType: order.cargoType,
          totalQuantity: order.totalQuantity,
          totalVolume: order.totalVolume,
          totalWeight: order.totalWeight,
          paymentMethod: paymentText,
          declaredValue: order.declaredValue,
          insuranceFee: order.insuranceFee,
          deliveryFee: order.deliveryFee,
          unloadingFee: order.unloadingFee,
          totalFreight: order.totalFreight,
          creator: order.operator,
          creatorPhone: order.operatorPhone,
          createTime: orderDate,
          driver: order.driver || '未分配',
          driverPhone: order.driverPhone || '',
          route: order.route || '',
          vehicle: order.vehiclePlate || '',
          status: statusCode
        };
      });

      total.value = orders.length;
      ElMessage.success(`查询成功，共找到${orders.length}条记录`);
    } else {
      tableData.value = [];
      total.value = 0;
      ElMessage.info('未找到符合条件的记录');
    }
  } catch (error) {
    console.error('查询出错:', error);
    ElMessage.error('查询失败，请稍后重试');
  } finally {
    loading.value = false;
  }
};

// 重置搜索条件
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    // @ts-ignore
    searchForm[key] = '';
  });
  orderStatus.value = 'all';
  paymentMethod.value = 'all';
  enabled.value = 'all';

  // 重置后自动加载所有数据
  handleSearch();
};

// 导出数据
const exportData = () => {
  console.log('导出数据');
  // 实现导出功能
};

// 查看详情
const viewDetail = (row: any) => {
  console.log('查看详情:', row);
  // 跳转到详情页面
  router.push(`/order/${row.id}`);
};

// 修改运费
const editFreight = (row: any) => {
  console.log('修改运费:', row);
  // 实现修改运费功能
};

// 表格容器引用
const tableWrapper = ref<HTMLElement | null>(null);

// 添加鼠标滚轮事件处理
onMounted(() => {
  handleSearch();

  const tableElement = tableWrapper.value;
  if (tableElement) {
    tableElement.addEventListener('wheel', (event) => {
      if (event.deltaY !== 0) {
        // 阻止默认的上下滚动行为
        event.preventDefault();
        // 将垂直滚动转换为水平滚动
        tableElement.scrollLeft += event.deltaY;
      }
    });
  }
});

// 处理分页变化
const handleSizeChange = (size: number) => {
  pageSize.value = size;
  handleSearch();
};

const handleCurrentChange = (page: number) => {
  currentPage.value = page;
  handleSearch();
};
</script>

<template>
  <div class="order-list-container">
    <!-- 搜索区域 -->
    <div class="search-area">
      <el-form :model="searchForm">
        <!-- 第一行 -->
        <div class="search-row">
          <el-form-item label="货号" class="search-item">
            <el-input
                v-model="searchForm.orderNumber"
                placeholder="请输入货号"
                clearable
            >
              <template #prefix>
                <el-icon>
                  <Search/>
                </el-icon>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item label="发货人" class="search-item">
            <el-input
                v-model="searchForm.senderInfo"
                placeholder="请输入发货人信息"
                clearable
            >
              <template #prefix>
                <el-icon>
                  <Search/>
                </el-icon>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item label="收货人" class="search-item">
            <el-input
                v-model="searchForm.receiverInfo"
                placeholder="请输入收货人信息"
                clearable
            >
              <template #prefix>
                <el-icon>
                  <Search/>
                </el-icon>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item label="状态" class="search-item">
            <el-select v-model="enabled" placeholder="请选择状态" clearable>
              <el-option label="全部" value="all"/>
              <el-option label="启用" value="enabled"/>
              <el-option label="停用" value="disabled"/>
            </el-select>
          </el-form-item>
        </div>

        <!-- 第二行 -->
        <div class="search-row">
          <el-form-item label="发货站" class="search-item">
            <el-select v-model="searchForm.senderStation" placeholder="请选择发货站" clearable>
              <el-option
                  v-for="item in stationOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="到达站" class="search-item">
            <el-select v-model="searchForm.destinationStation" placeholder="请选择到达站" clearable>
              <el-option
                  v-for="item in stationOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="中转站" class="search-item">
            <el-select v-model="searchForm.transferStation" placeholder="请选择中转站" clearable>
              <el-option
                  v-for="item in stationOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="开单日期" class="search-item date-range">
            <el-date-picker
                v-model="searchForm.startDate"
                type="date"
                placeholder="开始日期"
                class="date-picker"
            />
            <span class="date-separator">~</span>
            <el-date-picker
                v-model="searchForm.endDate"
                type="date"
                placeholder="结束日期"
                class="date-picker"
            />
          </el-form-item>

          <div class="search-buttons">
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </div>
        </div>
      </el-form>
    </div>

    <!-- 表格操作区域 -->
    <div class="table-operations">
      <div class="left-operations">
        <el-button type="primary" @click="$router.push('/order/create')">
          <el-icon>
            <Plus/>
          </el-icon>
          开单
        </el-button>
        <el-button @click="exportData">
          <el-icon>
            <Download/>
          </el-icon>
          导出
        </el-button>
      </div>

      <div class="table-filter">
        <el-radio-group v-model="orderStatus">
          <el-radio-button label="all">全部</el-radio-button>
          <el-radio-button label="waiting_load">待配载</el-radio-button>
          <el-radio-button label="waiting_accept">待接单</el-radio-button>
          <el-radio-button label="in_transit">运输中</el-radio-button>
          <el-radio-button label="waiting_sign">待签收</el-radio-button>
          <el-radio-button label="completed">已完成</el-radio-button>
          <el-radio-button label="cancelled">已取消</el-radio-button>
        </el-radio-group>
      </div>
    </div>

    <!-- 表格区域 -->
    <div class="order-table-wrapper" ref="tableWrapper">
      <el-table
          :data="tableData"
          style="width: 100%"
          border
          stripe
          highlight-current-row
          v-loading="loading"
          element-loading-text="加载数据中..."
          element-loading-spinner="el-icon-loading"
          element-loading-background="rgba(255, 255, 255, 0.8)"
      >
        <!-- 左侧固定列 -->
        <el-table-column type="selection" width="50" fixed="left"/>
        <el-table-column prop="id" label="货号" width="120" fixed="left"/>
        <el-table-column prop="waybillNumber" label="运单号" width="120" fixed="left"/>

        <!-- 中间可滚动列 -->
        <el-table-column prop="sender" label="发货人" min-width="100"/>
        <el-table-column prop="senderPhone" label="发货人电话" min-width="120"/>
        <el-table-column prop="senderAddress" label="发货人地址" min-width="200" show-overflow-tooltip/>
        <el-table-column prop="senderStation" label="发货站" min-width="100"/>
        <el-table-column prop="transferStation" label="中转站" min-width="100"/>
        <el-table-column prop="destinationStation" label="到达站" min-width="100"/>
        <el-table-column prop="receiver" label="收货人" min-width="100"/>
        <el-table-column prop="receiverPhone" label="收货人电话" min-width="120"/>
        <el-table-column prop="receiverAddress" label="收货人地址" min-width="200" show-overflow-tooltip/>
        <el-table-column prop="cargoType" label="货物类型" min-width="100"/>
        <el-table-column prop="totalQuantity" label="总数量" min-width="100"/>
        <el-table-column prop="totalVolume" label="总体积(方)" min-width="120"/>
        <el-table-column prop="totalWeight" label="总重量(KG)" min-width="120"/>
        <el-table-column prop="paymentMethod" label="付款方式" min-width="100"/>
        <el-table-column prop="declaredValue" label="声明价值" min-width="100"/>
        <el-table-column prop="insuranceFee" label="保费" min-width="100"/>
        <el-table-column prop="deliveryFee" label="配送费" min-width="100"/>
        <el-table-column prop="unloadingFee" label="卸货费" min-width="100"/>
        <el-table-column prop="totalFreight" label="总运费" min-width="100"/>
        <el-table-column prop="creator" label="开单人" min-width="100"/>
        <el-table-column prop="creatorPhone" label="开单人电话" min-width="120"/>
        <el-table-column prop="createTime" label="开单时间" min-width="160"/>
        <el-table-column prop="driver" label="司机" min-width="100"/>
        <el-table-column prop="driverPhone" label="司机电话" min-width="120"/>
        <el-table-column prop="route" label="线路" min-width="120"/>
        <el-table-column prop="vehicle" label="车辆" min-width="100"/>

        <!-- 右侧固定列 -->
        <el-table-column label="状态" width="100" fixed="right">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.status)">
              {{ statusTextMap[scope.row.status] }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="150" fixed="right">
          <template #default="scope">
            <el-button
                size="small"
                type="primary"
                text
                @click="viewDetail(scope.row)"
            >
              详情
            </el-button>
            <el-button
                size="small"
                type="warning"
                text
                @click="editFreight(scope.row)"
            >
              修改运费
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
            background
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="pageSize"
            :current-page="currentPage"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<style scoped>
.order-list-container {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

.search-area {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f8f8f8;
  border-radius: 4px;
}

.search-row {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 15px;
  align-items: center;
}

.search-item {
  margin-right: 15px;
  margin-bottom: 0;
  min-width: 200px;
}

.search-item :deep(.el-form-item__label) {
  width: 70px;
  text-align: right;
}

.date-range {
  display: flex;
  align-items: center;
  min-width: 400px;
}

.date-picker {
  width: 150px;
}

.date-separator {
  margin: 0 8px;
}

.search-buttons {
  margin-left: auto;
}

.table-operations {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.order-table-wrapper {
  /* 设置相对定位，使内部滚动区域相对于此定位 */
  position: relative;
  width: 100%;
  overflow: hidden;
  cursor: grab; /* 指示可以横向滚动 */
}

.order-table-wrapper:active {
  cursor: grabbing; /* 指示正在横向滚动 */
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

/* 确保表格内容超出时能够横向滚动 */
:deep(.el-table--scrollable-x) {
  overflow-x: auto;
}

/* 优化表格头部样式 */
:deep(.el-table__header) {
  background-color: #f5f7fa;
}

:deep(.el-table__header th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 600;
}

/* 自定义表格样式 */
:deep(.el-table--striped .el-table__body tr.el-table__row--striped td) {
  background-color: #fafafa;
}

:deep(.el-table__body tr:hover > td) {
  background-color: #f0f5ff !important;
}
</style> 